<template>
  <CardLarge title="监控" :height="height">
    <template #action>
      <template v-for="item in arrangeRadio">
        <el-icon
          class="arrange-btn"
          :class="{ 'is-active': splitNum === item.value }"
          @click="() => changeWndNum(item.value)">
          <SvgIcon :icon-name="item.iconName" />
        </el-icon>
        <el-divider class="arrange-divider" direction="vertical" />
      </template>
    </template>
    <template #default>
      <div id="divPlugin" class="player"></div>
    </template>
  </CardLarge>
</template>
<script setup>
import CardLarge from '@/components/CardLarge.vue';
import request from '@/utils/request.js';
import { ErrorCodes, showOPInfo, showCBInfo } from './HkPlayer.js';
import { chunk } from 'lodash-es';
import { shallowRef } from 'vue';

// 假数据
import { channelResData as _channelResData } from './假数据.js';

const props = defineProps({
  height: {
    type: [Number, String],
    default: 300,
  },
});

// 窗口分割数
const splitNum = shallowRef(3);
const arrangeRadio = shallowRef([
  {
    iconName: 'grid-1x1',
    value: 1,
  },
  {
    iconName: 'grid-2x2',
    value: 2,
  },
  {
    iconName: 'grid-3x3',
    value: 3,
  },
]);
const changeWndNum = (value) => {
  splitNum.value = value;
  const iType = parseInt(value, 10);
  WebVideoCtrl.I_ChangeWndNum(iType);
  console.log(`切换到${iType}x${iType}布局`);
  // startLoop();
};

const channelData = shallowRef([]);
const channelLoop = computed(() => {
  const size = splitNum.value * splitNum.value;
  return chunk(channelData.value, size);
});
const loopCurrent = shallowRef(0);

// 添加缺失的变量
const ipOption = shallowRef(new Set());
const ipVal = shallowRef('');
const currentWindowIndex = ref(0); // 当前窗口索引，用于自动分配播放窗口

// 设置代理Cookie函数
function setProxyCookies(playItem) {
  try {
    const { ip, port } = playItem;
    // 设置WebSocket代理相关的Cookie
    document.cookie = `webVideoCtrlProxyWs=ws://${ip}:${port}; path=/`;
    document.cookie = `webVideoCtrlProxyWss=wss://${ip}:${port}; path=/`;
    document.cookie = `webVideoCtrlProxyWsChannel=ws://${ip}:${port}; path=/`;
    console.log(`✅ 已设置代理Cookie: ${ip}:${port}`);
  } catch (error) {
    console.error('❌ 设置代理Cookie失败:', error);
  }
}

const loopTimer = shallowRef(null);
const startLoop = () => {
  stopLoop();
  loopCurrent.value = 0;
  const loopLen = channelLoop.value.length;
  if (loopLen <= 1) {
    return;
  }
  const { channelLoopInterval = 5 } = window.thresholdData;
  // 开启定时器
  loopTimer.value = setInterval(() => {
    const current = loopCurrent.value + 1;
    loopCurrent.value = current < loopLen ? current : 0;
    // 预览
    play();
  }, channelLoopInterval * 1000);
};
const stopLoop = () => {
  loopTimer.value && clearInterval(loopTimer.value);
};

// 初始化
const initWebVideoCtrl = () => {
  // 检查浏览器是否支持无插件
  var iRet = window.WebVideoCtrl.I_SupportNoPlugin();
  if (!iRet) {
    alert('当前浏览器版本过低，不支持无插件，请升级后再试！');
    return;
  }
  // 初始化插件参数及插入无插件
  WebVideoCtrl.I_InitPlugin('100%', '100%', {
    bWndFull: true, //是否支持单窗口双击全屏，默认支持 true:支持 false:不支持
    iPackageType: 2,
    //szColorProperty:"plugin-background:0000ff; sub-background:0000ff; sub-border:00ffff; sub-border-select:0000ff",   //2:PS 11:MP4
    iWndowType: 1,
    bNoPlugin: true,
    // cbSelWnd: function (xmlDoc) {
    //   g_iWndIndex = parseInt($(xmlDoc).find('SelectWnd').eq(0).text(), 10);
    //   var szInfo = '当前选择的窗口编号：' + g_iWndIndex;
    //   showCBInfo(szInfo);
    // },
    cbDoubleClickWnd: function (iWndIndex, bFullScreen) {
      var szInfo = '当前放大的窗口编号：' + iWndIndex;
      if (!bFullScreen) {
        szInfo = '当前还原的窗口编号：' + iWndIndex;
      }
      showCBInfo(szInfo);
    },
    cbEvent: function (iEventType, iParam1, iParam2) {
      if (2 == iEventType) {
        // 回放正常结束
        showCBInfo('窗口' + iParam1 + '回放结束！');
      } else if (-1 == iEventType) {
        showCBInfo('设备' + iParam1 + '网络错误！', 'error');
      } else if (3001 == iEventType) {
        // clickStopRecord(g_szRecordType, iParam1);
      }
    },
    cbRemoteConfig: function () {
      showCBInfo('关闭远程配置库！');
    },
    cbInitPluginComplete: function () {
      WebVideoCtrl.I_InsertOBJECTPlugin('divPlugin');
      console.log('🎬 WebVideoCtrl插件初始化完成');
      // 插件初始化完成后设置9宫格
      setTimeout(() => {
        try {
          WebVideoCtrl.I_ChangeWndNum(3);
          console.log('✅ 插件初始化完成后设置为9宫格');
        } catch (error) {
          console.error('❌ 插件初始化后设置9宫格失败:', error);
        }
      }, 100);
    },
    cbPluginErrorHandler: function (iWndIndex, iErrorCode, oError) {
      // 插件错误回调
      showCBInfo('窗口' + iWndIndex + '：' + ErrorCodes[iErrorCode], 'error');
      var oWndInfo = WebVideoCtrl.I_GetWindowStatus(iWndIndex),
        szInfo = '';

      if (oWndInfo != null) {
        WebVideoCtrl.I_Stop({
          success: function () {
            szInfo = '停止预览成功！';
            showOPInfo(oWndInfo.szDeviceIdentify + ' ' + szInfo);
          },
          error: function () {
            szInfo = '停止预览失败！';
            showOPInfo(oWndInfo.szDeviceIdentify + ' ' + szInfo, 'error');
          },
        });
      }
    },
    cbPerformanceLack: function () {
      // 性能不足回调
      showCBInfo('性能不足！', 'warning');
    },
    cbSecretKeyError: function (iWndIndex) {
      // 码流加密秘钥错误回调
      showCBInfo('窗口' + iWndIndex + '：码流加密秘钥错误！', 'error');
      var oWndInfo = WebVideoCtrl.I_GetWindowStatus(iWndIndex),
        szInfo = '';

      if (oWndInfo != null) {
        WebVideoCtrl.I_Stop({
          success: function () {
            szInfo = '停止预览成功！';
            showOPInfo(oWndInfo.szDeviceIdentify + ' ' + szInfo);
          },
          error: function () {
            szInfo = '停止预览失败！';
            showOPInfo(oWndInfo.szDeviceIdentify + ' ' + szInfo, 'error');
          },
        });
      }
    },
  });
};

// 登录
function clickLogin(playItem) {
  const { ip, port, user, pwd } = playItem;
  // iProtocol  1登录(http)  2登录(https)
  const iProtocol = 1;
  var szIP = ip,
    szPort = port,
    szUsername = user,
    szPassword = pwd;

  if ('' == szIP || '' == szPort) {
    return;
  }

  // sessionStorage.setItem('loginip', szIP); // 记录下。方便查看
  // sessionStorage.setItem('password', szPassword);

  var szDeviceIdentify = szIP + '_' + szPort;

  var iRet = WebVideoCtrl.I_Login(
    szIP,
    iProtocol,
    szPort,
    szUsername,
    szPassword,
    {
      success: function (xmlDoc) {
        showOPInfo(szDeviceIdentify + ' 登录成功！', 'success');
        // 添加到已登录设备列表
        if (ipOption && ipOption.value) {
          ipOption.value.add(szDeviceIdentify);
        }

        // 更新登录统计
        if (window.loginStats) {
          window.loginStats.success++;
          window.loginStats.pending--;
          console.log(`✅ ${szDeviceIdentify} 登录成功！当前统计:`, window.loginStats);
        }

        // 不设置Cookie，参考HkPlayer11111.vue的成功经验
        // setProxyCookies(playItem);

        // 登录成功后自动开始播放
        setTimeout(() => {
          // 为每个设备分配不同的窗口索引
          const windowIndex = currentWindowIndex.value;
          currentWindowIndex.value = (currentWindowIndex.value + 1) % 9; // 9宫格最多9个窗口

          // 使用假数据中的通道号
          const rtspPort = 554;
          const channelId = playItem.channel || 1; // 使用假数据中的通道号，默认1
          console.log(`开始播放设备: ${szDeviceIdentify}`);
          console.log(`播放参数: 窗口=${windowIndex}, 通道=${channelId}, RTSP端口=${rtspPort}`);

          // 检查窗口是否已被占用
          const oWndInfo = WebVideoCtrl.I_GetWindowStatus(windowIndex);
          if (oWndInfo != null) {
            console.log(`⚠️ 窗口${windowIndex}已被占用，先停止现有播放`);
            WebVideoCtrl.I_Stop({
              success: function () {
                console.log(`✅ 窗口${windowIndex}停止成功，开始新播放`);
                clickStartRealPlay(playItem, windowIndex, channelId, rtspPort);
              },
              error: function () {
                console.log(`❌ 窗口${windowIndex}停止失败，直接开始播放`);
                clickStartRealPlay(playItem, windowIndex, channelId, rtspPort);
              }
            });
          } else {
            clickStartRealPlay(playItem, windowIndex, channelId, rtspPort);
          }
        }, 5000 + (currentWindowIndex.value * 5000)); // 每个设备间隔5秒播放，避免并发冲突

        setTimeout(function () {
          if (ipVal && ipVal.value !== undefined) {
            ipVal.value = szDeviceIdentify;
          }
          // 获取通道信息（可选）
          try {
            const channelInfo = getChannelInfo(szDeviceIdentify);
            const portInfo = getDevicePort(szDeviceIdentify);
            console.log(`📋 设备 ${szDeviceIdentify} 通道信息:`, channelInfo);
            console.log(`🔌 设备 ${szDeviceIdentify} 端口信息:`, portInfo);
          } catch (error) {
            console.warn(`⚠️ 获取设备信息失败: ${szDeviceIdentify}`, error);
          }
        }, 10);
      },
      error: function (status, xmlDoc) {
        showOPInfo(szDeviceIdentify + ' 登录失败！', 'error');

        // 更新登录统计
        if (window.loginStats) {
          window.loginStats.failed++;
          window.loginStats.pending--;
          console.log(`❌ ${szDeviceIdentify} 登录失败！当前统计:`, window.loginStats);
        }
      },
    }
  );

  if (-1 == iRet) {
    showOPInfo(szDeviceIdentify + ' 已登录过！');
    clickStartRealPlay(playItem);
  }
}
// 退出 - 退出会自动停止szIP播放
function clickLogout(playItem) {
  const { ip, port } = playItem;
  var szDeviceIdentify = ip + '_' + port,
    szInfo = '';

  if (null == szDeviceIdentify) {
    return;
  }
  let WndSet = WebVideoCtrl.I_GetWndSet();
  var iRet = WebVideoCtrl.I_Logout(szDeviceIdentify);
  if (0 == iRet) {
    WndSet.forEach((element) => {
      if (element.szDeviceIdentify === szDeviceIdentify) {
        WebVideoCtrl.I_Stop({
          iIndex: element.iIndex,
          success: function () {
            szInfo = '停止取流成功！';
            showOPInfo(szDeviceIdentify + ' ' + szInfo, 'success');
          },
          error: function () {
            szInfo = '停止取流失败！';
            showOPInfo(szDeviceIdentify + ' ' + szInfo, 'error');
          },
        });
        WebVideoCtrl.I_SetSecretKey('', element.iIndex); // 清空码流秘钥
      }
    });
    szInfo = '退出成功！';

    if (ipOption && ipOption.value) {
      ipOption.value.delete(szDeviceIdentify);
    }
  } else {
    szInfo = '退出失败！';
  }
  showOPInfo(szDeviceIdentify + ' ' + szInfo, 'error');
}
// 获取通道
function getChannelInfo(_szDeviceIdentify) {
  var szDeviceIdentify = _szDeviceIdentify;
  var oSel = [];
  if (null == szDeviceIdentify) {
    return;
  }

  // 模拟通道
  WebVideoCtrl.I_GetAnalogChannelInfo(szDeviceIdentify, {
    async: false,
    success: function (xmlDoc) {
      var oChannels = $(xmlDoc).find('VideoInputChannel');

      $.each(oChannels, function (i) {
        var id = $(this).find('id').eq(0).text(),
          name = $(this).find('name').eq(0).text();
        if ('' == name) {
          name = 'Camera ' + (i < 9 ? '0' + (i + 1) : i + 1);
        }
        oSel.push({ id, name });
      });
      showOPInfo(szDeviceIdentify + ' 获取模拟通道成功！', 'success');
    },
    error: function (status, xmlDoc) {
      showOPInfo(szDeviceIdentify + ' 获取模拟通道失败！', 'error');
    },
  });
  // // 数字通道
  // WebVideoCtrl.I_GetDigitalChannelInfo(szDeviceIdentify, {
  //   async: false,
  //   success: function (xmlDoc) {
  //     var oChannels = $(xmlDoc).find('InputProxyChannelStatus');
  //
  //     $.each(oChannels, function (i) {
  //       var id = $(this).find('id').eq(0).text(),
  //         name = $(this).find('name').eq(0).text(),
  //         online = $(this).find('online').eq(0).text();
  //       if ('false' == online) {
  //         // 过滤禁用的数字通道
  //         return true;
  //       }
  //       if ('' == name) {
  //         name = 'IPCamera ' + (i < 9 ? '0' + (i + 1) : i + 1);
  //       }
  //       oSel.push({ id, name });
  //     });
  //     showOPInfo(szDeviceIdentify + ' 获取数字通道成功！', 'success');
  //   },
  //   error: function (status, xmlDoc) {
  //     showOPInfo(szDeviceIdentify + ' 获取数字通道失败！', 'error');
  //   },
  // });
  // // 零通道
  // WebVideoCtrl.I_GetZeroChannelInfo(szDeviceIdentify, {
  //   async: false,
  //   success: function (xmlDoc) {
  //     var oChannels = $(xmlDoc).find('ZeroVideoChannel');
  //
  //     $.each(oChannels, function (i) {
  //       var id = $(this).find('id').eq(0).text(),
  //         name = $(this).find('name').eq(0).text();
  //       if ('' == name) {
  //         name = 'Zero Channel ' + (i < 9 ? '0' + (i + 1) : i + 1);
  //       }
  //       if ('true' == $(this).find('enabled').eq(0).text()) {
  //         // 过滤禁用的零通道
  //         oSel.push({ id, name });
  //       }
  //     });
  //     showOPInfo(szDeviceIdentify + ' 获取零通道成功！', 'success');
  //   },
  //   error: function (status, xmlDoc) {
  //     showOPInfo(szDeviceIdentify + ' 获取零通道失败！', 'error');
  //   },
  // });

  return oSel;
}
// 获取端口
function getDevicePort(_szDeviceIdentify) {
  var szDeviceIdentify = _szDeviceIdentify;

  if (null == szDeviceIdentify) {
    return;
  }

  var oPort = WebVideoCtrl.I_GetDevicePort(szDeviceIdentify);
  if (oPort != null) {
    // 设备端口
    const deviceport = oPort.iDevicePort;
    const rtspport = oPort.iRtspPort;
    showOPInfo(szDeviceIdentify + ' 获取端口成功！', 'success');
    return { deviceport, rtspport };
  } else {
    showOPInfo(szDeviceIdentify + ' 获取端口失败！', 'error');
  }
}

// 开始预览 - 参考HkPlayer11111.vue的成功实现
function clickStartRealPlay(playItem, g_iWndIndex, iChannelID, rtspport) {
  const { ip, port } = playItem;
  var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex),
    szDeviceIdentify = ip + '_' + port,
    iRtspPort = parseInt(rtspport, 10),
    iChannelID = parseInt(iChannelID, 10),
    bZeroChannel = false, // 是否禁用零通道
    szInfo = '',
    iStreamType = 1; // 1主码流 2子码流 3第三码流 - 使用子码流减少带宽压力

  const bProxy = false; //false 开始预览(直连) true 开始预览(代理)
  console.log('播放参数:', { oWndInfo, szDeviceIdentify, iRtspPort, iChannelID, bProxy });

  if (null == szDeviceIdentify) {
    return;
  }

  var startRealPlay = function () {
    console.log(`🎬 开始播放请求: ${szDeviceIdentify}, 窗口: ${g_iWndIndex}`);

    // 设置超时检测
    let hasCallback = false;
    const timeoutId = setTimeout(() => {
      if (!hasCallback) {
        console.warn(`⚠️ 播放请求超时: ${szDeviceIdentify}, 窗口: ${g_iWndIndex} (10秒无响应)`);
        showOPInfo(szDeviceIdentify + ' 播放请求超时！', 'warning');
      }
    }, 10000);

    WebVideoCtrl.I_StartRealPlay(szDeviceIdentify, {
      iWndIndex: g_iWndIndex,
      iRtspPort: iRtspPort,
      iStreamType: iStreamType,
      iChannelID: iChannelID,
      bZeroChannel: bZeroChannel,
      bProxy, // ws取流协议是否要过Nginx
      success: function () {
        hasCallback = true;
        clearTimeout(timeoutId);
        szInfo = '开始预览成功！';
        showOPInfo(szDeviceIdentify + ' ' + szInfo, 'success');
        console.log('✅ 播放成功:', szDeviceIdentify, '窗口:', g_iWndIndex);

        // 触发播放成功事件
        if (window.debugPlay && window.debugPlay.onPlaySuccess) {
          window.debugPlay.onPlaySuccess(szDeviceIdentify);
        }
      },
      error: function (status, xmlDoc) {
        hasCallback = true;
        clearTimeout(timeoutId);
        if (403 === status) {
          szInfo = '设备不支持Websocket取流！';
        } else if (status === 1003) {
          szInfo = '设备连接失败或通道不存在！';
        } else if (status === 1004) {
          szInfo = '设备忙或资源不足！';
        } else {
          szInfo = '开始预览失败！';
        }
        showOPInfo(szDeviceIdentify + ' ' + szInfo, 'error');
        console.error('❌ 播放失败:', szDeviceIdentify, '状态码:', status, '窗口:', g_iWndIndex);

        // 尝试备用通道
        if (status === 1003 && iChannelID === 1) {
          console.log(`🔄 尝试备用通道2...`);
          setTimeout(() => {
            clickStartRealPlay(playItem, g_iWndIndex, 2, iRtspPort);
          }, 2000);
        } else if (status === 1003 && iChannelID === 2) {
          console.log(`🔄 尝试备用通道3...`);
          setTimeout(() => {
            clickStartRealPlay(playItem, g_iWndIndex, 3, iRtspPort);
          }, 2000);
        }
      },
    });
  };

  if (oWndInfo != null) {
    // 已经在播放了，先停止
    WebVideoCtrl.I_Stop({
      success: function () {
        startRealPlay();
      },
    });
  } else {
    startRealPlay();
  }
}

const loginAll = (channelResData = []) => {
  console.log('🔍 开始登录设备，设备数量:', channelResData.length);
  console.log('📋 设备列表:', channelResData);

  // 登录统计
  window.loginStats = {
    total: channelResData.length,
    success: 0,
    failed: 0,
    pending: channelResData.length,
    devices: channelResData // 保存设备列表
  };

  // 延迟登录，避免请求过快
  channelResData.forEach((playItem, index) => {
    setTimeout(() => {
      console.log(`🚀 登录设备 ${index + 1}/${channelResData.length}:`, playItem);
      clickLogin(playItem);
    }, index * 2000); // 每个设备间隔2秒登录
  });

  // 定期显示登录统计
  const statsInterval = setInterval(() => {
    console.log('📊 登录统计:', window.loginStats);
    if (window.loginStats.pending === 0) {
      clearInterval(statsInterval);
      console.log('✅ 所有设备登录完成！');

      // 直接启动9宫格同时播放
      setTimeout(() => {
        console.log('🎬 启动9宫格同时播放');
        // 直接调用多窗口播放，不使用轮播
        const devices = window.loginStats?.devices || correctedDeviceList.slice(0, 9);
        console.log('🎯 要播放的设备列表:', devices);

        // 分时启动，每个窗口间隔3秒，避免并发冲突
        devices.forEach((device, index) => {
          setTimeout(() => {
            const playItem = { ...device, user: 'admin', pwd: 'Hik77177' };
            console.log(`🎬 启动窗口 ${index}:`, playItem);
            clickStartRealPlay(playItem, index, device.channel, 554);
          }, (index + 1) * 3000); // 3秒间隔
        });
      }, 3000);
    }
  }, 5000);
};
// 全部退出
const logoutAll = () => {
  channelData.value.forEach((item) => {
    clickLogout(item);
  });
};
const play = () => {};

// 添加全局调试函数
window.debugLayout = {
  set9Grid: () => {
    try {
      WebVideoCtrl.I_ChangeWndNum(3);
      console.log('手动设置为9宫格');
    } catch (error) {
      console.error('设置失败:', error);
    }
  },
  set4Grid: () => {
    try {
      WebVideoCtrl.I_ChangeWndNum(2);
      console.log('手动设置为4宫格');
    } catch (error) {
      console.error('设置失败:', error);
    }
  },
  set1Grid: () => {
    try {
      WebVideoCtrl.I_ChangeWndNum(1);
      console.log('手动设置为单窗口');
    } catch (error) {
      console.error('设置失败:', error);
    }
  },
  checkWebVideoCtrl: () => {
    console.log('WebVideoCtrl对象:', typeof WebVideoCtrl);
    console.log('I_ChangeWndNum方法:', typeof WebVideoCtrl?.I_ChangeWndNum);
    console.log('当前splitNum值:', splitNum.value);
  },
  force9Grid: () => {
    console.log('🔧 强制设置为9宫格...');
    splitNum.value = 3;
    if (typeof WebVideoCtrl !== 'undefined' && WebVideoCtrl.I_ChangeWndNum) {
      WebVideoCtrl.I_ChangeWndNum(3);
      console.log('✅ 强制设置完成');
    } else {
      console.error('❌ WebVideoCtrl不可用');
    }
  }
};

// 添加播放调试函数
window.debugPlay = {
  // 手动播放指定设备
  playDevice: (ip, port, windowIndex = 0, channel = 1, rtspPort = 554) => {
    const playItem = { ip, port, user: 'admin', pwd: 'Hik77177', channel: channel };
    console.log('🎬 手动播放设备:', playItem);
    clickStartRealPlay(playItem, windowIndex, channel, rtspPort);
  },
  // 播放所有设备
  playAll: () => {
    console.log('🎬 播放所有设备');
    channelData.value.forEach((item, index) => {
      setTimeout(() => {
        const channelId = 1;
        clickStartRealPlay(item, index, channelId, 554);
      }, index * 1000);
    });
  },
  // 测试不同通道
  testChannels: (ip, port) => {
    const channels = [1, 2, 3, 4];
    channels.forEach((channel, index) => {
      setTimeout(() => {
        const playItem = { ip, port, user: 'admin', pwd: 'Hik77177', channel: channel };
        console.log(`测试通道 ${channel}`);
        clickStartRealPlay(playItem, index, channel, 554);
      }, index * 2000);
    });
  },
  // 检查设备状态
  checkDeviceStatus: (ip, port) => {
    const szDeviceIdentify = ip + '_' + port;
    const loginState = WebVideoCtrl.I_GetLoginState(szDeviceIdentify);
    const wndInfo = WebVideoCtrl.I_GetWndInfo(szDeviceIdentify);
    console.log('设备状态:', { szDeviceIdentify, loginState, wndInfo });
  },
  // 检查所有窗口状态
  checkAllWindows: () => {
    console.log('🔍 检查所有窗口状态:');
    for (let i = 0; i < 9; i++) {
      const wndInfo = WebVideoCtrl.I_GetWindowStatus(i);
      console.log(`窗口${i}:`, wndInfo);
    }
  },
  // 检查登录状态
  checkLoginStatus: () => {
    console.log('🔍 检查所有设备登录状态:');
    const devices = ['192.168.12.2_80', '192.168.12.3_80', '192.168.12.4_80', '192.168.12.5_80', '192.168.12.6_80', '192.168.12.7_80', '192.168.12.8_80', '192.168.12.9_80', '192.168.12.10_80'];
    devices.forEach(device => {
      const loginState = WebVideoCtrl.I_GetLoginState(device);
      console.log(`${device}: 登录状态=${loginState}`);
    });
  },
  // 检查播放状态
  checkPlayStatus: () => {
    console.log('🔍 检查所有窗口播放状态:');
    for (let i = 0; i < 9; i++) {
      const wndInfo = WebVideoCtrl.I_GetWindowStatus(i);
      if (wndInfo) {
        console.log(`窗口${i}: 正在播放 ${wndInfo.szDeviceIdentify}`);
      } else {
        console.log(`窗口${i}: 空闲`);
      }
    }
  },
  // 强制播放所有设备
  forcePlayAll: () => {
    console.log('🎬 强制播放所有设备:');
    const devices = [
      {ip: '192.168.12.2', port: '80', channel: 1},
      {ip: '192.168.12.3', port: '80', channel: 1},
      {ip: '192.168.12.4', port: '80', channel: 1},
      {ip: '192.168.12.5', port: '80', channel: 1},
      {ip: '192.168.12.6', port: '80', channel: 1},
      {ip: '192.168.12.7', port: '80', channel: 1},
      {ip: '192.168.12.8', port: '80', channel: 1},
      {ip: '192.168.12.9', port: '80', channel: 1},
      {ip: '192.168.12.10', port: '80', channel: 1}
    ];
    devices.forEach((device, index) => {
      setTimeout(() => {
        const playItem = { ...device, user: 'admin', pwd: 'Hik77177' };
        console.log(`强制播放设备 ${index + 1}:`, playItem);
        clickStartRealPlay(playItem, index, device.channel, 554);
      }, index * 1000);
    });
  },
  // 检查实际播放状态
  checkActualPlayStatus: () => {
    console.log('🔍 检查实际播放状态:');
    for (let i = 0; i < 9; i++) {
      const wndInfo = WebVideoCtrl.I_GetWindowStatus(i);
      if (wndInfo) {
        console.log(`窗口${i}: 正在播放 ${wndInfo.szDeviceIdentify}`);
        console.log(`  - 设备标识: ${wndInfo.szDeviceIdentify}`);
        console.log(`  - 窗口索引: ${wndInfo.iIndex}`);
        console.log(`  - 播放状态: ${wndInfo.iPlayState || '未知'}`);
      } else {
        console.log(`窗口${i}: 空闲`);
      }
    }
  },
  // 尝试逐个播放
  playOneByOne: () => {
    console.log('🎬 逐个播放设备:');
    const devices = [
      {ip: '192.168.12.2', port: '80', channel: 1},
      {ip: '192.168.12.3', port: '80', channel: 1},
      {ip: '192.168.12.4', port: '80', channel: 1}
    ];

    let currentIndex = 0;
    const playNext = () => {
      if (currentIndex < devices.length) {
        const device = devices[currentIndex];
        const playItem = { ...device, user: 'admin', pwd: 'Hik77177' };
        console.log(`播放设备 ${currentIndex + 1}:`, playItem);
        clickStartRealPlay(playItem, currentIndex, device.channel, 554);
        currentIndex++;
        setTimeout(playNext, 15000); // 15秒后播放下一个
      }
    };
    playNext();
  },
  // 测试前3个设备（避免设备限制）
  playFirstThree: () => {
    console.log('🎬 测试前3个设备:');
    const devices = [
      {ip: '192.168.12.2', port: '80', channel: 1},
      {ip: '192.168.12.3', port: '80', channel: 1},
      {ip: '192.168.12.4', port: '80', channel: 1}
    ];
    devices.forEach((device, index) => {
      setTimeout(() => {
        const playItem = { ...device, user: 'admin', pwd: 'Hik77177' };
        console.log(`播放设备 ${index + 1}:`, playItem);
        clickStartRealPlay(playItem, index, device.channel, 554);
      }, index * 3000); // 间隔3秒
    });
  },
  // 真正的逐个播放（等前一个成功后再播放下一个）
  playSequentially: () => {
    console.log('🎬 逐个播放所有设备（等前一个成功后再播放下一个）:');
    const devices = [
      {ip: '192.168.12.2', port: '80', channel: 1},
      {ip: '192.168.12.3', port: '80', channel: 1},
      {ip: '192.168.12.4', port: '80', channel: 1},
      {ip: '192.168.12.5', port: '80', channel: 1},
      {ip: '192.168.12.6', port: '80', channel: 1},
      {ip: '192.168.12.7', port: '80', channel: 1},
      {ip: '192.168.12.8', port: '80', channel: 1},
      {ip: '192.168.12.9', port: '80', channel: 1},
      {ip: '192.168.12.10', port: '80', channel: 1}
    ];

    let currentIndex = 0;
    let isPlaying = false;
    let timeoutId = null;

    // 停止所有现有播放
    WebVideoCtrl.I_Stop({
      success: function () {
        console.log('✅ 停止所有现有播放成功');
      },
      error: function () {
        console.log('❌ 停止现有播放失败，继续执行');
      }
    });

    const playNext = () => {
      if (currentIndex < devices.length && !isPlaying) {
        isPlaying = true;
        const device = devices[currentIndex];
        const playItem = { ...device, user: 'admin', pwd: 'Hik77177' };
        console.log(`🎬 开始播放设备 ${currentIndex + 1}/${devices.length}:`, playItem);

        // 先停止当前播放
        WebVideoCtrl.I_Stop({
          success: function () {
            console.log(`✅ 停止当前播放成功，开始播放设备 ${device.ip}`);
          },
          error: function () {
            console.log(`❌ 停止当前播放失败，直接开始播放设备 ${device.ip}`);
          }
        });

        // 2秒后开始播放
        setTimeout(() => {
          // 监听播放成功事件
          const originalSuccess = window.debugPlay.onPlaySuccess;
          window.debugPlay.onPlaySuccess = (deviceId) => {
            console.log(`✅ 设备 ${deviceId} 播放成功，准备播放下一个`);
            if (timeoutId) {
              clearTimeout(timeoutId);
              timeoutId = null;
            }
            isPlaying = false;
            currentIndex++;
            setTimeout(playNext, 3000); // 3秒后播放下一个
          };

          clickStartRealPlay(playItem, 0, device.channel, 554); // 始终使用窗口0

          // 15秒超时保护
          timeoutId = setTimeout(() => {
            if (isPlaying) {
              console.log(`⚠️ 设备 ${device.ip} 播放超时，继续下一个`);
              isPlaying = false;
              currentIndex++;
              setTimeout(playNext, 3000);
            }
          }, 15000);
        }, 2000);
      } else if (currentIndex >= devices.length) {
        console.log('🎉 所有设备播放完成！');
      }
    };

    // 3秒后开始第一个设备
    setTimeout(playNext, 3000);
  },
  // 轮播模式（只播放一个设备，每隔30秒切换）
  playCarousel: () => {
    console.log('🎠 轮播模式：只播放前五个设备，每隔30秒切换');
    const devices = [
      {ip: '192.168.12.2', port: '80', channel: 1},
      {ip: '192.168.12.3', port: '80', channel: 1},
      {ip: '192.168.12.4', port: '80', channel: 1},
      {ip: '192.168.12.5', port: '80', channel: 1},
      {ip: '192.168.12.6', port: '80', channel: 1}
    ];

    let currentIndex = 0;

    const playNext = () => {
      // 先停止所有播放
      WebVideoCtrl.I_Stop({
        success: function () {
          console.log('✅ 停止当前播放成功');
        },
        error: function () {
          console.log('❌ 停止当前播放失败');
        }
      });

      // 2秒后播放下一个设备
      setTimeout(() => {
        const device = devices[currentIndex];
        const playItem = { ...device, user: 'admin', pwd: 'Hik77177' };
        console.log(`🎠 轮播播放设备 ${currentIndex + 1}/${devices.length}:`, playItem);

        clickStartRealPlay(playItem, 0, device.channel, 554); // 始终使用窗口0

        currentIndex = (currentIndex + 1) % devices.length;

        // 10秒后切换到下一个设备（参考文章经验）
        setTimeout(playNext, 10000);
      }, 2000);
    };

    playNext();
  },
  // 停止所有播放
  stopAll: () => {
    console.log('🛑 停止所有播放');
    WebVideoCtrl.I_Stop({
      success: function () {
        console.log('✅ 停止所有播放成功');
      },
      error: function () {
        console.log('❌ 停止播放失败');
      }
    });
  },
  // 重置播放状态
  reset: () => {
    console.log('🔄 重置播放状态');
    window.debugPlay.stopAll();
    // 清除所有定时器
    if (window.debugPlay.timeoutId) {
      clearTimeout(window.debugPlay.timeoutId);
      window.debugPlay.timeoutId = null;
    }
  },
  // 9宫格同时播放（分时启动，参考文章经验）
  playMultiWindow: () => {
    console.log('🎬 9宫格同时播放（分时启动，参考文章经验）');
    const devices = [
      {ip: '192.168.12.2', port: '80', channel: 1},
      {ip: '192.168.12.3', port: '80', channel: 1},
      {ip: '192.168.12.4', port: '80', channel: 1},
      {ip: '192.168.12.5', port: '80', channel: 1},
      {ip: '192.168.12.6', port: '80', channel: 1},
      {ip: '192.168.12.7', port: '80', channel: 1},
      {ip: '192.168.12.8', port: '80', channel: 1},
      {ip: '192.168.12.9', port: '80', channel: 1},
      {ip: '192.168.12.10', port: '80', channel: 1}
    ];

    // 每个窗口间隔3秒启动，避免并发冲突
    devices.forEach((device, index) => {
      setTimeout(() => {
        const playItem = { ...device, user: 'admin', pwd: 'Hik77177' };
        console.log(`🎬 启动窗口 ${index}:`, playItem);
        clickStartRealPlay(playItem, index, device.channel, 554);
      }, (index + 1) * 3000); // 3秒间隔
    });
  }
};
onMounted(() => {
  initWebVideoCtrl();
  window.addEventListener('resize', resize);

  // 尝试多种方式设置9宫格
  const trySet9Grid = () => {
    if (typeof WebVideoCtrl !== 'undefined' && WebVideoCtrl.I_ChangeWndNum) {
      try {
        // 检查插件是否完全初始化
        if (WebVideoCtrl.I_GetWndSet && typeof WebVideoCtrl.I_GetWndSet === 'function') {
          WebVideoCtrl.I_ChangeWndNum(3);
          console.log('✅ 成功设置为9宫格');
          return true;
        } else {
          console.log('⏳ WebVideoCtrl插件还未完全初始化，等待...');
          return false;
        }
      } catch (error) {
        console.error('❌ 设置9宫格失败:', error);
        return false;
      }
    }
    return false;
  };

  // 立即尝试
  setTimeout(trySet9Grid, 100);
  setTimeout(trySet9Grid, 500);
  setTimeout(trySet9Grid, 1000);
  setTimeout(trySet9Grid, 2000);

  getData().then((res) => {
    console.log('📡 API响应:', res);
    console.log('📄 响应内容:', res.content);

    try {
      const deviceList = JSON.parse(res.content);
      console.log('🔧 解析后的设备列表:', deviceList);

      // 修正通道号：将接口返回的101改为1
      const correctedDeviceList = deviceList.map(device => ({
        ...device,
        channel: device.channel === 101 ? 1 : device.channel
      }));
      console.log('✅ 修正后的设备列表:', correctedDeviceList);

      // 登录前9个设备，实现9宫格播放
      const testDevices = correctedDeviceList.slice(0, 9);
      console.log('🎬 9宫格模式：登录前9个设备', testDevices);
      loginAll([...testDevices]);
    } catch (error) {
      console.error('❌ 解析设备数据失败:', error);
      console.log('📄 原始内容:', res.content);
    }

    // 登录完成后再次尝试
    setTimeout(trySet9Grid, 3000);
  }).catch((error) => {
    console.error('❌ 获取设备数据失败:', error);
  });
});
onUnmounted(() => {
  window.removeEventListener('resize', resize);
  logoutAll(); // 全部退出
  stopLoop(); //关闭循环
});
// 设置播放容器的宽高并监听窗口大小变化
const resize = () => {
  WebVideoCtrl?.I_Resize('100%', '100%');
};

const getData = () => {
  return request({
    method: 'post',
    url: '/DataScreen/database/lulan',
    data: {
      'method': 'getVideoStreamPath',
      'format': 'JSON',
      'content': `{\"id\":1,\"startTime\":null,\"endTime\":null}`,
    },
  });
};
</script>
<style lang="scss" scoped>
.arrange-btn {
  height: vw(32);
  width: vw(32);
  font-size: vw(28);
  color: #fff;
  cursor: pointer;

  &.is-active {
    color: #00fffc;
  }
  &:nth-last-of-type(1) {
    & + .arrange-divider {
      display: none;
    }
  }
}
.arrange-divider {
  --el-border-color: #00fffc;
  height: vw(28);
}

.player {
  height: 100%;
}
</style>
